package cn.xtcode.domain.trade.service.lock;

import cn.xtcode.domain.trade.adapter.repository.ITradeRepository;
import cn.xtcode.domain.trade.model.aggregate.GroupBuyOrderAggregate;
import cn.xtcode.domain.trade.model.entity.*;
import cn.xtcode.domain.trade.model.valobj.GroupBuyProgressVO;
import cn.xtcode.domain.trade.service.ITradeLockOrderService;
import cn.xtcode.domain.trade.service.lock.factory.TradeRuleFilterFactory;
import cn.xtcode.types.design.framework.link.model2.chain.BusinessLinkedList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author xt-code
 * @Description:
 * @Create 2025/5/9 18:46
 */
@Slf4j
@Service
public class TradeLockOrderService implements ITradeLockOrderService {
    @Resource
    private ITradeRepository repository;

    @Resource
    private BusinessLinkedList<TradeLockRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> tradeRuleFilter;

    /**
     * 查询用户关于outTradeNo的支付情况
     *
     * @param userId
     * @param outTradeNo
     * @return
     */
    @Override
    public MarketPayOrderEntity queryNoPayMarketPayOrderByOutTradeNo(String userId, String outTradeNo) {
        log.info("拼团交易-查询未支付营销订单:{} outTradeNo:{}", userId, outTradeNo);
        
        return repository.queryNoPayMarketPayOrderByOutTradeNo(userId, outTradeNo);
    }

    /**
     * 查询拼团进度
     *
     * @param teamId
     * @return
     */
    @Override
    public GroupBuyProgressVO queryGroupBuyProgress(String teamId) {
        log.info("拼团交易-查询拼单进度:{}", teamId);
        return repository.queryGroupBuyProgress(teamId);
    }

    @Override
    public MarketPayOrderEntity lockMarketPayOrder(UserEntity userEntity, PayActivityEntity payActivityEntity, PayDiscountEntity payDiscountEntity) throws Exception {
        log.info("拼团交易-锁定营销优惠支付订单:{} activityId:{} goodsId:{}", userEntity.getUserId(), payActivityEntity.getActivityId(), payDiscountEntity.getGoodsId());

        //交易规则过滤
        TradeLockRuleFilterBackEntity tradeLockRuleFilterBackEntity = tradeRuleFilter.apply(TradeLockRuleCommandEntity.builder()
                        .activityId(payActivityEntity.getActivityId())
                        .userId(userEntity.getUserId())
                        .build(),
                new TradeRuleFilterFactory.DynamicContext());

        Integer userTakeOrderCount = tradeLockRuleFilterBackEntity.getUserTakeOrderCount();

        GroupBuyOrderAggregate groupBuyOrderAggregate = GroupBuyOrderAggregate.builder()
                .userEntity(userEntity)
                .payActivityEntity(payActivityEntity)
                .payDiscountEntity(payDiscountEntity)
                .userTakeOrderCount(userTakeOrderCount)
                .build();

        //通过聚合对象去锁单
        return repository.lockMarketPayOrder(groupBuyOrderAggregate);
    }
}
